import { app } from 'electron'
import { dirname, join } from 'path'
import fs from 'fs'

export default function setupPaths(): void {
  // 在一切之前将所有 Chromium/Electron 数据目录指向安装目录
  const baseDirEarly = app.isPackaged ? dirname(process.execPath) : undefined
  if (baseDirEarly) {
    const dataDir = join(baseDirEarly, 'data')
    const tempDir = join(baseDirEarly, 'temp')
    const cacheDir = join(baseDirEarly, 'cache')
    try {
      if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true })
      if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true })
      if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true })
    } catch {
      /* empty */
    }
    app.setPath('userData', dataDir)
    app.setPath('temp', tempDir)
    // 启用磁盘缓存并指向安装目录
    app.commandLine.appendSwitch('disk-cache-dir', cacheDir)
    app.commandLine.appendSwitch('gpu-disk-cache-dir', cacheDir)
  }
}
